package org.squabble.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.squabble.service.AccountService;
import org.squabble.web.account.RegisterCommand;


@Component(value="registerValidator")
public class RegisterValidator implements Validator {

	@Autowired
	AccountService accountService;

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return RegisterCommand.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		RegisterCommand rc = (RegisterCommand) arg0;
		if (accountService.nameExists(rc.getName())) {
			errors.rejectValue("name", "RegisterCommand.username[in.use]");
		}
		if (accountService.emailExists(rc.getEmail())) {
			errors.rejectValue("email", "RegisterCommand.email[in.use]");
		}
	}

}
